#!/usr/local/bin/python2.7

import time, pickle, sys

from stripcrawler import *
from doccrawler import *
from rstdbmaker import *
from delimwriter import *
from djangowriter import *
from constants import *
from xmldb import *
from xmlwriter import *

from dbase import *

if __name__ == '__main__':
    arg = ''
    if len(sys.argv) > 1:
        arg = sys.argv[1].lower()

    dbase = DBase()

    if arg == 'convert':
        doccrawler = DocCrawler()
        try:
            doccrawler.run()
        except KeyboardInterrupt as err:
            print 'Keyboard Interrupt: Processing was stopped.'

        doccrawler.saveLog()

    elif arg == 'strip':
        print 'Loading pickled data...'
        dbase.load()
        stripcrawler = StripCrawler()

        print 'Stripping data from word docs...'
        try:
            stripcrawler.run()
        except KeyboardInterrupt as err:
            print 'Keyboard Interrupt: Processing was stopped.'
            stripcrawler.saveLog()

        comps = stripcrawler.completed_components
        dbase.addComponents(comps)

        print 'Pickling data...'
        dbase.save()
        print str(len(comps)) + ' components were stripped.'

    elif arg == 'rst-db':
        print 'Loading pickled data...'
        dbase.load()
        rstmaker = RstMaker()
        rstmaker.addComponents(dbase.components)
        rstmaker.problems = dbase.problems
        print 'Generating restructuredText...'
        rstmaker.generateRstIndex()

    elif arg == 'delim-db':
        print 'Loading pickled data...'
        dbase.load()
        delimer = DelimWriter(delimiter = Constants.delim_chars)
        delimer.addComponents(dbase.components)
        print 'Generating delimited data...'
        delimer.saveFile()

    elif arg == 'xml-files':
        print 'Loading pickled data...'
        dbase.load()
        mywriter = XMLWriter()

        print 'Generating xml data...'
        for comp in dbase.components:
            mywriter.component = comp
            try:
                mywriter.saveFile()
            except Exception as err:
                print err

    elif arg == 'xml-db':
        print 'Loading pickled data...'
        dbase.load()
        xml_db = XMLdb()

        xml_db.addComponents(dbase.components)
        print 'Generating xml data...'
        xml_db.saveFile()

    elif arg == 'database-direct':
        print 'Loading pickled data...'
        dbase.load()
        mywriter = DjangoWriter()
        comps = dbase.components
        print 'Using django to update mysql...'
        for comp in comps:
            mywriter.component = comp
            mywriter.saveFile()
        print 'Done.'

    else:
        print 'Loading pickled data...'
        dbase.load()
        print dbase

